<?php
namespace addons\qiniuoss;

use think\Addons;
use think\facade\Db;
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
use app\common\annotation\HooksAnotation;
use app\member\service\User as home_user;
use app\admin\model\Attachment as Attachment_Model;

class Plugin extends Addons
{
    // 该插件的基础信息
    public $info = [
        'name' => 'qiniuoss',
        'title' => '七牛云oss插件',
        'description' => '七牛云oss插件',
        'status' => 1,
        'author' => 'ZengCMS',
        'require' => '1.0.0',
        'version' => '1.0.0',
        'website' => '',
        'images'=>'addons/qiniuoss/images/qiniuoss.jpg',
        'group'=>'',
        'is_hook'=>1,
    ];
    public $menu = [
        'is_nav' => 0,
    ];
    // 上传管理员ID
    public $admin_id = 0;
    // 上传用户ID
    public $user_id  = 0;
    // 会员组
    public $groupid = 0;
    // 是否后台
    public $isadmin     = 0;
    // 插件配置
    public $config = array();
    // 初始化
    protected function init()
    {
        // 判断是否安装
        if(!isAddonInstall($this->name)){
            return false;
        }
        include_once ADDONS_PATH . '/qiniu/SDK/autoload.php';
        $this->isLogin();
        $this->config = getAddonConfig('qiniu');
    }
    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $upload_driver = Db::name('config')->where(['name' => 'upload_driver'])->find();
        if (!$upload_driver) {
            $this->error = '未找到【上传驱动】配置';
            return false;
        }
        $options = parse_attr($upload_driver['extra']);
        if (isset($options['qiniu'])) {
            $this->error = '已存在名为【qiniu】的上传驱动';
            return false;
        }
        $upload_driver['extra'] .= PHP_EOL . 'qiniu:七牛云';
        $result = Db::name('config')
        ->where(['name' => 'upload_driver'])
        ->update(['extra'=>$upload_driver['extra']]);
        if (false === $result) {
            $this->error = '上传驱动设置失败';
            return false;
        }
        return true;
    }
    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        $upload_driver = Db::name('config')->where(['name' => 'upload_driver'])->find();
        if ($upload_driver) {
            $options = parse_attr($upload_driver['extra']);
            if (isset($options['qiniu'])) {
                unset($options['qiniu']);
            }
            $options = $this->implode_attr($options);
            $result  = Db::name('config')
            ->where(['name' => 'upload_driver'])
            ->update(['extra' => $options, 'value' => $upload_driver['value'] == 'qiniu'?'local':$upload_driver['value']]);
            if (false === $result) {
                $this->error = '上传驱动设置失败';
                return false;
            }
        }
        return true;
    }
    /**
     * 插件使用方法
     * @return bool
     */
    public function enabled()
    {
        return true;
    }
    /**
     * 插件禁用方法
     * @return bool
     */
    public function disabled()
    {
        return true;
    }
    /**
     * name 钩子(行为)名称
     * description 钩子描述
     * type 类型(1:视图,2:控制器)
     * system 是否系统
     * status 状态
     * @HooksAnotation(description="上传本地临时附件",type="2")
     * @return [type] [description]
     */
    public function UploadOssAfter($params = [])
    {
        // 判断是否调用七牛云的
        if(sys_config('upload_driver') !== 'qiniu'){
            return '';
        }
        $this->init();
        $error_msg = '';
        if ($this->config['accessKey'] == '') {
            $error_msg = '未填写七牛【AccessKey】';
        } elseif ($this->config['secrectKey'] == '') {
            $error_msg = '未填写七牛【SecretKey】';
        } elseif ($this->config['bucket'] == '') {
            $error_msg = '未填写七牛【Bucket】';
        } elseif ($this->config['domain'] == '') {
            $error_msg = '未填写七牛【Domain】';
        }
        if ($error_msg != '') {
            return json_encode([
                'code'  => -1,
                'info'  => $error_msg,
                'state' => $error_msg,   // 兼容百度ueditor
                'error'   => 1,          // 兼容kindeditor
                'success' => 0,          // 兼容editormd
                'message' => $error_msg, // 兼容editormd和kindeditor
            ],JSON_UNESCAPED_UNICODE);
        }
        $file   = $params['file'];
        $info['name'] = $file->getOriginalName();
        $info['mime'] = $file->getOriginalMime();
        $info['tmp_name'] = $file->getPathName();
        $suffix = strtolower(pathinfo($info['name'], PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        // 要上传文件的本地路径
        $filePath = $info['tmp_name'];
        // 上传到七牛后保存的文件名
        $file_name = explode('.', $info['name']);
        $ext       = end($file_name);
        $key       = $params['dir'] . '/' . date('Ymd') . '/' . $file->hash('md5') . '.' . $ext;
        // 构建鉴权对象
        $auth = new Auth($this->config['accessKey'], $this->config['secrectKey']);
        // 初始化空间
        $bucket = $this->config['bucket'];
        // 生成上传 Token
        $token = $auth->uploadToken($bucket, $key);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return json_encode([
                'code'    => -1,
                'info'    => '上传失败:' . $err,
                'state'   => '上传失败:' . $err, // 兼容百度ueditor
                'error'   => 1,                 // 兼容kindeditor
                'success' => 0,                 // 兼容editormd
                'message' => '上传失败:' . $err, // 兼容editormd和kindeditor
            ],JSON_UNESCAPED_UNICODE);
        } else {
            // 获取附件信息
            $path = rtrim($this->config['domain'], '/') . '/' . $key;
            // 获取文件类型
            if (strpos($info['mime'], 'image/') !== false) {
                $file_type = 'image';
            } elseif (strpos($info['mime'], 'video/') !== false) {
                $file_type = 'video';
            }else{
                $file_type = 'file';
            }
            $data = [
                'aid'         => $this->admin_id,
                'uid'         => $this->user_id,
                'group_id'    => $params['group_id']??0,
                'file_name'   => basename($path),
                'file_type'   => $file_type,
                'name'        => $info['name'],
                'module'      => $params['module'],
                'path'        => $path,
                'thumb'       => '',
                'url'         => '',
                'mime'        => $info['mime'],
                'ext'         => $suffix,
                'size'        => $file->getSize(),
                'md5'         => $file->hash('md5'),
                'sha1'        => $file->hash('sha1'),
                'driver'      => 'qiniu',
                'status'      => 1,
                'sort'        => 100,
                'create_time' => time(),
                'update_time' => time(),
            ];
            if ($file_add = Attachment_Model::create($data)) {
                // 返回结果
                return json_encode([
                    'code'    => 0,
                    'info'    => $data['name'] . '上传成功',
                    'id'      => $file_add['id'],
                    'path'    => $data['path'],
                    'state'   => "SUCCESS",     // 上传状态，上传成功时必须返回"SUCCESS" 兼容百度
                    'url'     => $data['path'], // 返回的地址，兼容百度和editormd
                    'title'   => $data['name'], // 附件名，兼容百度ueditor
                    'error'   => 0,             // 兼容kindeditor
                    'success' => 1,             // 兼容editormd
                    'message' => $data['name'], // 附件名，兼容editormd和kindeditor
                ],JSON_UNESCAPED_UNICODE);
            } else {
                return json_encode([
                    'code'    => -1,
                    'info'    => '上传成功,写入数据库失败',
                    'state'   => '上传成功,写入数据库失败', //兼容百度ueditor
                    'error'   => 1,                       //兼容kindeditor
                    'success' => 0,                       //兼容editormd
                    'message' => '上传成功,写入数据库失败', //兼容editormd和kindeditor
                ],JSON_UNESCAPED_UNICODE);
            }
        }
    }
    /**
     * name 钩子(行为)名称
     * description 钩子描述
     * type 类型(1:视图,2:控制器)
     * system 是否系统
     * status 状态
     * @HooksAnotation(description="上传本地附件",type="2")
     * @return [type] [description]
     */
    public function UploadOss($params = [])
    {
        // 判断是否调用七牛云的
        if(sys_config('upload_driver') !== 'qiniu'){
            return '';
        }
        $this->init();
        $error_msg = '';
        if ($this->config['accessKey'] == '') {
            $error_msg = '未填写七牛【accessKey】';
        } elseif ($this->config['secrectKey'] == '') {
            $error_msg = '未填写七牛【secrectKey】';
        } elseif ($this->config['bucket'] == '') {
            $error_msg = '未填写七牛【bucket】';
        } elseif ($this->config['domain'] == '') {
            $error_msg = '未填写七牛【domain】';
        }
        if ($error_msg != '') {
            return json_encode([
                'code'    => -1,
                'info'    => $error_msg,
                'state'   => $error_msg, //兼容百度ueditor
                'error'   => 1,          //兼容kindeditor
                'success' => 0,          //兼容editormd
                'message' => $error_msg, //兼容editormd和kindeditor
            ],JSON_UNESCAPED_UNICODE);
        }
        $key = str_replace('uploads/', '', $params['path']);
        // 构建鉴权对象
        $auth = new Auth($this->config['accessKey'], $this->config['secrectKey']);
        // 初始化空间
        $bucket = $this->config['bucket'];
        // 生成上传 Token
        $token = $auth->uploadToken($bucket, $key);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, get_file_path($params['path'],2));
        if ($err !== null) {
            return json_encode([
                'code'    => -1,
                'info'    => '上传失败:' . $err,
                'state'   => '上传失败:' . $err, //兼容百度ueditor
                'error'   => 1,                 //兼容kindeditor
                'success' => 0,                 //兼容editormd
                'message' => '上传失败:' . $err, //兼容editormd和kindeditor
            ],JSON_UNESCAPED_UNICODE);
        } else {
            $path = rtrim($this->config['domain'], '/') . '/' . $key;
            $params['path'] = $path;
            $params['driver'] = 'qiniu';
            if ($file_add = Attachment_Model::create($params)) {
                // 返回结果
                return json_encode([
                    'code'    => 0,
                    'info'    => $params['name'] . '上传成功',
                    'id'      => $file_add['id'],
                    'path'    => $path,
                    'state'   => "SUCCESS",      // 上传状态，上传成功时必须返回"SUCCESS" 兼容百度
                    'title'   => $params['name'],// 附件名，兼容百度ueditor
                    'url'     => $path,          // 返回的地址，兼容百度ueditor和editormd
                    'error'   => 0,              // 兼容kindeditor
                    'success' => 1,              // 兼容editormd
                    'message' => $params['name'],// 附件名，兼容editormd和kindeditor
                ],JSON_UNESCAPED_UNICODE);
            } else {
                return json_encode([
                    'code'    => -1,
                    'info'    => '上传成功,写入数据库失败',
                    'state'   => '上传成功,写入数据库失败', //兼容百度ueditor
                    'error'   => 1,                       //兼容kindeditor
                    'success' => 0,                       //兼容editormd
                    'message' => '上传成功,写入数据库失败', //兼容editormd和kindeditor
                ],JSON_UNESCAPED_UNICODE);
            }
        }
    }
    /**
     * name 钩子(行为)名称
     * description 钩子描述
     * type 类型(1:视图,2:控制器)
     * system 是否系统
     * status 状态
     * @HooksAnotation(description="删除oss附件",type="2")
     * @return [type] [description]
     */
    public function DeleteOss($params = [])
    {
        // 判断是否调用七牛云的
        if(sys_config('upload_driver') !== 'qiniu'){
            return '';
        }
        $this->init();
        $key = str_replace(rtrim($this->config['domain'], '/') . '/', '', $params['path']);
        $auth = new Auth($this->config['accessKey'], $this->config['secrectKey']);
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        $err = $bucketManager->delete($this->config['bucket'], $key);
        return true;
    }
    protected function isLogin()
    {
        if (is_login() > 0) {
            $this->isadmin  = 1;
            $this->admin_id = is_login();
        } elseif (home_user::instance()->isLogin()) {
            $this->user_id = home_user::instance()->id;
            $this->groupid = home_user::instance()->groupid ? home_user::instance()->groupid : 8;
        } else {
            $this->admin_id = 0;
            $this->user_id = 0;
        }
    }
    protected function implode_attr($array = [])
    {
        $result = [];
        foreach ($array as $key => $value) {
            $result[] = $key . ':' . $value;
        }
        return empty($result) ? '' : implode(PHP_EOL, $result);
    }
}
